<?php

namespace app\admin\service;

use app\model\TaskUserResultModel;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use think\Service;

class TaskService extends Service
{
    /**
     * 完成情况选择器
     * @param int $key
     * @return int[]|string[]
     */
    public function CompletionStatus(int $key = 0): array
    {
        $data = [
            [
                'id' => 1,
                'name' => '0~10%',
                'value' => [0, 10],
            ],
            [
                'id' => 2,
                'name' => '10~20%',
                'value' => [10, 20],
            ],
            [
                'id' => 3,
                'name' => '20~30%',
                'value' => [20, 30],
            ],
            [
                'id' => 4,
                'name' => '30~40%',
                'value' => [30, 40],
            ],
            [
                'id' => 5,
                'name' => '40~50%',
                'value' => [40, 50],
            ],
            [
                'id' => 6,
                'name' => '50~60%',
                'value' => [50, 60],
            ],
            [
                'id' => 7,
                'name' => '60~70%',
                'value' => [60, 70],
            ],
            [
                'id' => 8,
                'name' => '70~80%',
                'value' => [70, 80],
            ],
            [
                'id' => 9,
                'name' => '80~90%',
                'value' => [80, 90],
            ],
            [
                'id' => 10,
                'name' => '90~100%',
                'value' => [90, 100],
            ]
        ];
        return $key?$data[$key-1]:$data;
    }

    /**
     * 权限选项配置
     * @param int $key
     * @return array|string
     */
    public function getResultReadAuth(int $key = 0): array|string
    {
        $data = [
            1 => '管理员',
            2 => '咨询师',
            3 => '用户',
            4 => '家长'
        ];
        return $data[$key] ?? $data;
    }

    /**
     * 转换权限
     * @param $str
     * @return string
     */
    public function getResultReadAuthName($str): string
    {
        if (empty($str)) return '';
        $data = explode(",", $str);
        foreach ($data as &$value) {
            $value = $this->getResultReadAuth($value);
        }
        return implode("、", $data);
    }

    /**
     * 导出任务已参与名单
     * @param array $data
     * @param int $is_finish
     * @return string
     */
    public function exportTaskUser(array $data, int $is_finish): string
    {
        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        // 设置工作表标题
        if ($is_finish == 1){
            $sheet->setTitle('任务已参与名单');
        }else{
            $sheet->setTitle('任务未参与名单');
        }
        // 设置单元格数据
        $sheet->setCellValue('A1', '名称');
        $sheet->setCellValue('B1', '联系方式');
        $sheet->setCellValue('C1', '性别');
        $sheet->setCellValue('D1', '年龄');
        $sheet->setCellValue('E1', '任务参与情况');
        $sheet->setCellValue('F1', '身份证号');
        $sheet->setCellValue('G1', '注册账号');
//        $sheet->setCellValue('H1', '所在系别/学部');
        $sheet->setCellValue('H1', '所在部门');
//        $sheet->setCellValue('J1', '班级编号');
        $sheet->setCellValue('I1', '部门内部编号');
//        $sheet->setCellValue('L1', '学籍状态');
        $sheet->setCellValue('J1', '部门管理员');
        if (!empty($data)) {
            $key = 2;
            foreach ($data as $item) {
                if ($item['is_finish'] != $is_finish) continue;
                //学籍状态
                $student_name = match ($item['student_status']) {
                    0 => '不限',
                    1 => '在读',
                    2 => '已毕业',
                    3 => '已退学',
                    4 => '休学',
                    default => '--',
                };
                // 设置单元格数据
                $sheet->setCellValue('A'.$key, $item['user_name']??'--');
                $sheet->setCellValue('B'.$key, $item['phone']??'--');
                $sheet->getStyle('B'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                $sheet->setCellValue('C'.$key, $item['sex'] == 1 ? '男' : '女');
                $sheet->setCellValue('D'.$key, $item['age']?:'--');
                $sheet->setCellValue('E'.$key, $item['is_finish'] == 1? '已完成' :'未完成');
                $sheet->setCellValue('F'.$key, $item['id_card']?:'--');
                $sheet->getStyle('F'.$key)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
                $sheet->setCellValue('G'.$key, $item['username']?:'--');
//                $sheet->setCellValue('H'.$key, $item['ascription_name']??'--');
                $sheet->setCellValue('H'.$key, $item['department_name']??'--');
//                $sheet->setCellValue('J'.$key, '--');
                $sheet->setCellValue('I'.$key, $item['user_number']?:'--');
//                $sheet->setCellValue('L'.$key, $student_name);
                $sheet->setCellValue('J'.$key, $item['department_admin']??'--');
                $key++;
            }
        }
        $writer = new Xlsx($spreadsheet);
        $ext = '.xlsx';
        $save_name = '/export/task_user'.date('Ym').'/'.date('d').'_'.time().uniqid();
        $file_path  = dirname('./public' . $save_name.$ext);
        folder_build($file_path);
        $writer->save('./public' . $save_name . $ext);
        return oss('./public' . $save_name . $ext, $ext);
    }

    /**
     * 导出结果数据
     * @param int $unit_id
     * @param array $where
     * @return mixed
     */
    public function exportData(int $unit_id,array $where): mixed
    {
        $TaskUserResultModel = new TaskUserResultModel();
        $data = $TaskUserResultModel->where($where)->with([
            'user' => function ($query) {
                $query->with(['unitName']);
            },
            'TaskFactorScore' => function ($query) {
                $query->with([
                    'RatingScaleFactor','RatingScaleFactorLevel'
                ]);
            },
            'RatingScaleFactorWarningModel'
        ])->select()->toArray();

        // 创建新的Spreadsheet对象
        $spreadsheet = new Spreadsheet();
        // 获取活动的工作表
        $sheet = $spreadsheet->getActiveSheet();
        // 设置工作表标题
        $sheet->setTitle('测试结果数据');
        // 设置单元格数据
        $sheet->setCellValue('A1', '测试时间');
        $sheet->setCellValue('B1', '单位');
        $sheet->setCellValue('C1', '部门');
        $sheet->setCellValue('D1', '姓名');
        $sheet->setCellValue('E1', '性别');
        $sheet->setCellValue('F1', '账号');
        $k = ['G','H','I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
            'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ',
            'BA', 'BB', 'BC', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BK', 'BL', 'BM', 'BN', 'BO', 'BP', 'BQ', 'BR', 'BS', 'BT', 'BU', 'BV', 'BW', 'BX', 'BY', 'BZ',
            'CA', 'CB', 'CC', 'CD', 'CE', 'CF', 'CG', 'CH', 'CI', 'CJ', 'CK', 'CL', 'CM', 'CN', 'CO', 'CP', 'CQ', 'CR', 'CS', 'CT', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ',
            'DA', 'DB', 'DC', 'DD', 'DE', 'DF', 'DG', 'DH', 'DI', 'DJ', 'DK', 'DL', 'DM', 'DN', 'DO', 'DP', 'DQ', 'DR', 'DS', 'DT', 'DU', 'DV', 'DW', 'DX', 'DY', 'DZ',
            'EA', 'EB', 'EC', 'ED', 'EE', 'EF', 'EG', 'EH', 'EI', 'EJ', 'EK', 'EL', 'EM', 'EN', 'EO', 'EP', 'EQ', 'ER', 'ES', 'ET', 'EU', 'EV', 'EW', 'EX', 'EY', 'EZ',
            'FA', 'FB', 'FC', 'FD', 'FE', 'FF', 'FG', 'FH', 'FI', 'FJ', 'FK', 'FL', 'FM', 'FN', 'FO', 'FP', 'FQ', 'FR', 'FS', 'FT', 'FU', 'FV', 'FW', 'FX', 'FY', 'FZ',
            'GA', 'GB', 'GC', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GJ', 'GK', 'GL', 'GM', 'GN', 'GO', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GV', 'GW', 'GX', 'GY', 'GZ'];

        $UserService = new UserService($this->app);
        $departmentData = $UserService->getNotDelDepartmentAffiliationAll($unit_id);
        foreach ($data as $key => $item) {
            if ($key == 0) {
                $i = 0;
                foreach ($item['TaskFactorScore'] as $v) {
                    $sheet->setCellValue($k[$i] . '1', $v['factor_name']);
                    $i++;
                }
                foreach ($item['TaskFactorScore'] as $kk => $v) {
                    if ($kk == 0) continue;
                    $sheet->setCellValue($k[$i] . '1', $v['factor_name']);
                    $i++;
                }
                $sheet->setCellValue($k[$i] . '1', '预警结果');
            }
            $key = $key + 2;
            $sheet->setCellValue('A' . $key, date('Y-m-d H:i:s', $item['time']));
            $sheet->setCellValue('B' . $key, $item['unit_name']);
            $sheet->setCellValue('C' . $key, $departmentData[$item['department_id']]['all_name']??'--');
            $sheet->setCellValue('D' . $key, $item['user_name']);
            $sheet->setCellValue('E' . $key, $item['sex'] == 1 ? '男' : '女');
            $sheet->setCellValue('F' . $key, $item['username'] . ' ');
            $j = 0;
            foreach ($item['TaskFactorScore'] as $v) {
                $sheet->setCellValue($k[$j] . $key, $v['score']);
                $j++;
            }
            foreach ($item['TaskFactorScore'] as $kk => $v) {
                if ($kk == 0) continue;
                preg_match('/\（(.*?)\）/', $v['factor_level_name'], $level_name);
                $sheet->setCellValue($k[$j] . $key, $level_name[1] ?? '');
                $j++;
            }
            $sheet->setCellValue($k[$j] . $key, $item['is_warning'] ? $item['warning_name'] : '正常');
        }
        $writer = new Xlsx($spreadsheet);
        $ext = '.xlsx';
        $save_name = '/export/task_user'.date('Ym').'/'.date('d').'_'.time().uniqid();
        $file_path  = dirname('./public' . $save_name.$ext);
        folder_build($file_path);
        $writer->save('./public' . $save_name . $ext);
        return oss('./public' . $save_name . $ext, $ext);
    }

}